var express = require('express');
var axios = require('axios');
var router = express.Router();
var sha1 = require('sha1');
var config = require('../config/config.js').config;
var api = require('../service/api')
var handleEvent = require('../controller/handleEvent.js')
var responseShop = require('../controller/responseShop.js')

var data = {
  access_token_main: '', //通过网页授权access_token可以进行授权后接口调用
  jsapi_ticket: '', //jsapi_ticket是公众号用于调用微信JS接口的临时票据
  openId: '' //用户的唯一标识码
}

// 获取access_token和jsapi_ticket
api.getToken_JsApi().then(obj => {
  data.access_token_main = obj.access_token
  data.jsapi_ticket = obj.jsapi_ticket

  console.log('data.jsapi_ticket', data.jsapi_ticket)

  let APPID = config.wechat.appID
  let REDIRECT_URI = 'http://syangserver.ngrok.xiaomiqiu.cn/response'
  let code = 'code'
  let SCOPE = 'snsapi_userinfo'  // 需要用户授权
  let loginUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=${code}&scope=${SCOPE}&state=STATE#wechat_redirect`
  let url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token_main}`
  let menu = {
    "button": [
      {
        "type": "view",  //view表示跳转
        "name": "**商城",
        "url": "http://syangwechar.ngrok.xiaomiqiu.cn/shop"
      },
      {
        "type": "click",   //表示事件
        "name": "戳一下",
        "key": "clickEvent"   //事件的key可自定义,微信服务器会发送到指定的服务器用于识别事件做出相应回应
      },
      {
        "name": "菜单",
        "sub_button": [  //二级菜单
          {
            "type": "view",
            "name": "登录",
            "url": loginUrl,
            "sub_button": []
          },
          {
            "type": "view",
            "name": "搜索",
            "url": "http://syangwechar.ngrok.xiaomiqiu.cn/shop"
          },
          {
            "type": "click",
            "name": "赞一下我们",
            "key": "V1001_GOOD"
          }]
      }]
  }

// 创建菜单,发送http请求
  axios.post(url, menu, {
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }).then(function (dt) {
    console.log('创建菜单请求已发出', dt.data)
  })
});

/* GET home page. */
router.get('/page', function (req, res, next) {
  res.render('index', {title: '吹牛拍马'});
});
router.get('/access_token', function (req, res, next) {
  var url = 'https://api.weixin.qq.com/cgi-bin/token'
  axios.get(url, {
    params: {
      grant_type: 'client_credential',
      appid: config.wechat.appID,
      secret: config.wechat.appsecret
    }
  }).then(userinfo => {
    config.wechat.access_token = userinfo.data.access_token
  })
});

function defautPage(req, res, next) {
  var token = config.wechat.token
  var signature = req.query.signature
  var nonce = req.query.nonce
  var timestamp = req.query.timestamp
  var echostr = req.query.echostr
  var str = [token, timestamp, nonce].sort().join('')
  var sha = sha1(str)

  if (sha === signature) {
    res.send(echostr + '');
  } else {
    res.send("error");
  }
}

// router.get('/', defautPage);

// 处理用户发送来的消息, 包括文字和点击事件
router.post('/', handleEvent.msg)

router.get('/process_get', function (req, res) {
  // 输出 JSON 格式
  var response = {
    "first_name": req.query.first_name,
    "last_name": req.query.last_name
  };
  console.log(response);
  res.send(JSON.stringify(response));
});

// 响应shop路由
router.get('/shop', (req, res) => {
  res.render('shop')
})

// 获取用户权限后跳转到response路由
router.get('/response', responseShop.shop)

// 生成签名用于wx.config
router.get('/getWxConfig', (req, res) => {
  var noncestr = req.query.nonceStr //前端传过来的随机字符串

  var timestamp = parseInt(new Date().getTime() / 1000) + '' //获取当前时间戳, 单位秒

  var url = req.query.url //获取前端页面的url, 不包括#及之后的内容

  //按照微信的官方说法要将用于生成签名的noncestr timestamp url jsapi_ticket 按照ASCII码由小到大排序, 以键值对的形式
  //拼接成字符串, "jsapi_ticket".charCodeAt()可查询
  var str = `jsapi_ticket=${data.jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`

  // 使用哈希加密成签名
  var signature = sha1(str)

  // 返回给前端
  res.json({
    appId: config.wechat.appID,
    signature: signature,
    timestamp: timestamp,
    jsapiTicket: data.jsapi_ticket,
    noncestr: noncestr,
    test: 123
  })
});

router.get('/getUserInfo', responseShop.userinfo);

module.exports = router;
